﻿using AutoMapper;
using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Models.Project;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules;
using Modules.Project;
using PmSoft.Entity;
using PmSoft.Utilities;

namespace ManagementApi.Controllers.CorpPannel
{
    /// <summary>
    /// 项目管理员-完工销户申请
    /// </summary>
    [Route("/api/v1/corp/completed")]
    [ApiController]
    [Authorize(Roles = "Corp")]
    public class ProjectCompletedController : ControllerBase
    {
        private readonly ProjectCompletedService projectCompletedService;
        private readonly CorpApplicationContext applicationContext;
        private readonly IMapper mapper;
        private readonly ProjectOwnAuthorizer ownAuthorizer;
        private readonly ProjectGuaranteePaymentService projectGuaranteePaymentService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="projectCompletedService"></param>
        /// <param name="applicationContext"></param>
        /// <param name="mapper"></param>
        /// <param name="ownAuthorizer"></param>
        /// <param name="projectGuaranteePaymentService"></param>
        public ProjectCompletedController(ProjectCompletedService projectCompletedService, CorpApplicationContext applicationContext, IMapper mapper
            , ProjectOwnAuthorizer ownAuthorizer, ProjectGuaranteePaymentService projectGuaranteePaymentService
            )
        {
            this.projectCompletedService = projectCompletedService;
            this.applicationContext = applicationContext;
            this.mapper = mapper;
            this.ownAuthorizer = ownAuthorizer;
            this.projectGuaranteePaymentService = projectGuaranteePaymentService;
        }

        #region 完工销户申请

        /// <summary>
        /// 新增完工销户申请
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost("create")]
        public ApiResult CreateProjectCompleted(ProjectCompletedEditForm form)
        {
            if (!applicationContext.IsLumpContractorCorp())
                return ApiResult.Failure("对不起，您暂时不能申请完工销户");
            if (projectCompletedService.ExistsByProjectId(applicationContext.CurrentProjectInfo.ProjectId)) return ApiResult.Failure("该项目已存在完工销户申请");
            ProjectCompleted entity = new();
            mapper.Map(form, entity);
            entity.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
            projectCompletedService.Create(entity, form.dicAttachments);
            return ApiResult.Success("创建成功");
        }

        /// <summary>
        /// 编辑完工销户申请
        /// </summary>
        /// <param name="id"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPut("update/{id}")]
        public ApiResult UpdateProjectCompleted(int id, ProjectCompletedEditForm form)
        {
            if (!applicationContext.IsLumpContractorCorp())
                return ApiResult.Failure("对不起，您暂时不能编辑完工销户");
            var entity = projectCompletedService.GetProjectCompleted(id);
            if (entity == null) return ApiResult.Failure("未查询到完工销户申请信息");
            if (entity.AuditType == ProjectConstants.完工销户申请状态.审核通过) return ApiResult.Failure("完工销户申请信息已通过");

            #region 验证数据权限

            ownAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(entity.ProjectId);

            #endregion 验证数据权限

            mapper.Map(form, entity);
            entity.AuditType = ProjectConstants.完工销户申请状态.待审核;
            projectCompletedService.Update(entity, form.dicAttachments);
            return ApiResult.Success("修改成功");
        }

        /// <summary>
        /// 删除完工销户申请
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete("{ids}")]
        public ApiResult DeleteProjectCompleted(string ids)
        {
            if (!applicationContext.IsLumpContractorCorp()) 
                return ApiResult.Failure("对不起，您暂时不能删除完工销户");
            var entitys = projectCompletedService.GetProjectCompleteds(ValueUtility.ConvertToList<int>(ids));

            #region 验证数据权限

            ownAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(entitys.Select(i => i.ProjectId));

            #endregion 验证数据权限

            projectCompletedService.Deleted(ValueUtility.ConvertToList<int>(ids));
            return ApiResult.Success("删除成功");
        }

        /// <summary>
        /// 完工销户申请表单数据
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public ApiResult<ProjectCompletedDto> GetProjectCompleted(int id)
        {
            if (id == 0)
            {
                ProjectCompleted projectCompleted = new ProjectCompleted();
                projectCompleted.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
                var payment = projectGuaranteePaymentService.GetProjectGuaranteePaymentByProjectId(projectCompleted.ProjectId);
                if (payment != null && payment.GuaranteeAccountType == 保证金类型.保证金账户)
                {
                    projectCompleted.RefundableAmount = payment.Paid;
                }
                return ApiResult<ProjectCompletedDto>.Success(projectCompleted.AsDto(applicationContext));
            }
            ProjectCompleted? data = projectCompletedService.GetProjectCompleted(id);
            if (data == null)
                return ApiResult<ProjectCompletedDto>.Failure("完工销户申请不存在");

            #region 验证数据权限

            ownAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(data.ProjectId);

            #endregion 验证数据权限

            return ApiResult<ProjectCompletedDto>.Success(data.AsDto(applicationContext));
        }

        /// <summary>
        /// 获取完工销户申请列表(分页)
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        [HttpGet("page")]
        public ApiResult<PageDto<ProjectCompletedDto>> QueryProjectCompleteds([FromQuery] ProjectCompletedQuery query, int pageNum = 1, int pageSize = 20)
        {
            if (!query.ProjectId.HasValue) query.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
            var data = projectCompletedService.GetProjectCompleteds(query, pageNum, pageSize);
            var dtos = data.AsPageDto(source => { return source.AsDto(applicationContext); });
            return ApiResult<PageDto<ProjectCompletedDto>>.Success(dtos);
        }

        #endregion 完工销户申请
    }
}